<?php //-->
/*
 * This file is part a custom application package.
 * (c) 2011-2012 Christian Blanquera <cblanquera@gmail.com>
 */

/**
 * Default logic to output a page
 */
class Front_Page_Rephrase extends Front_Page {
	/* Constants
	-------------------------------*/
	/* Public Properties
	-------------------------------*/
	/* Protected Properties
	-------------------------------*/
	protected $_errors = array();
	
	protected $_title = 'Support Rephrase: %s';
	protected $_class = 'support ask';
	protected $_template = '/rephrase.phtml';
	
	/* Private Properties
	-------------------------------*/
	/* Magic
	-------------------------------*/
	/* Public Methods
	-------------------------------*/
	public function render() {
		//authentication zone
		front()->authenticate();
		
		//get the post id from the URL
		$post = front()->registry()->get('request', 'variables', 0);
		//and make it into a model
		$post = front()->post()->model($post);
		
		//set the page title
		$this->_title = sprintf($this->_title, $post['post_title']);
		
		//if the user is not the author and if the user is not an admin (post_active==2)
		if($post->getPostUser() != front()->registry()->get('session', 'user')->getUserId()
		&& front()->registry()->get('session', 'user')->getUserActive() != 2) {
			//if this is a question
			if($post['post_parent'] == 0) {
				//redirect to that question
				front()->redirect('/question/'.$post['post_slug']);
			}
			
			//it could be an answer, let's get the parent
			$post = front()->post()->getRow($post['post_parent']);
			
			//if this is a question
			if($post['post_parent'] == 0) {
				//redirect to that question
				front()->redirect('/question/'.$post['post_slug']);
			}
			
			//it could have been a comment
			$post = front()->post()->getRow($post['post_parent']);
			//finally, redirect to the question
			front()->redirect('/question/'.$post['post_slug']);
		}
		
		//if there was a form submit and it's valid
		if(!empty($_POST) && $this->_validate()) {
			//process and redirect
			$this->_process($post);
		}
		
		//if the post title is set
		if(isset($_POST['title'])) {
			//set the title
			$post->setPostTitle($_POST['title']);
		}
		
		//if the post detail is set
		if(isset($_POST['detail'])) {
			//set the detail
			$post->setPostDetail($_POST['detail']);
		}
		
		//send the post, errors and tags
		$this->_body['post'] 	= $post;
		$this->_body['errors'] 	= $this->_errors;
		$this->_body['tags'] 	= array();
		
		//if there are tags already
		if(isset($_POST['tags'])) {
			//add it to boy tags
			foreach($_POST['tags'] as $tag) {
				if(!trim($tag)) {
					continue;
				}
				
				$this->_body['tags'][] = $tag;
			}
		//there is no post tags
		} else {
			//attempt to populate tags
			$tags = $post->getCategories();
			foreach($tags as $tag) {
				$this->_body['tags'][] = $tag['category_title'];
			}		
		}
		
		return $this->_page();
	}
	
	/* Protected Methods
	-------------------------------*/
	protected function _validate() {
		$this->_errors = array();
		
		if(isset($_POST['title']) && !trim($_POST['title'])) {
			$this->_errors['title'] = 'Title cannot be empty.';
		}
		
		if(!trim($_POST['detail'])) {
			$this->_errors['detail'] = 'Detail cannot be empty.';
		}
		
		return empty($this->_errors);
	}
	
	protected function _process($post) {
		//set up the post model and get the categories
		$categories = $post
			->setPostDetail($_POST['detail'])
			->setPostUpdated(time())
			->formatTime('post_updated')
			->getCategories();
		
		//if this is not a question
		if($post['post_type'] != 'question') {
			//there are no tags, so just save it
			$post = front()->post()->model($post->save()->getPostParent());
			//and redirect out
			front()->redirect('/question/'.$post->getPostSlug());
		} 
		
		//this is a question, set the title
		$post->setPostTitle($_POST['title']);
		
		//remove all categories
		foreach($categories as $category) {
			$post->removeCategory($category['category_id']);
		}
		
		//get tag root
		$root = front()
			->category()
			->search()
			->filterByCategoryParent(0)
			->filterByCategoryTitle('tag')
			->setRange(1)
			->getModel();
		
		//loop through tags
		$tags = $_POST['tags'];
		foreach($tags as $i => $name) {
			//if there's no name
			if(!trim($name)) {
				//skip it
				unset($tags[$i]);
				continue;
			}
			
			//we are lower casing all tags
			$name = strtolower($name);
			
			//check to see if tag exists
			$tag = front()
				->category()
				->search()
				->filterByCategoryParent($root->getCategoryId())
				->filterByCategoryTitle($name)
				->setRange(1)
				->getModel();
			
			//if it doesn't
			if(!$tag) {
				//create it
				$tag = front()
					->category()
					->model()
					->setCategoryTitle($name)
					->setCategoryParent($root->getCategoryId())
					->setCategoryUpdated(time())
					->formatTime('category_updated')
					->save();	
			}
			
			//replace the tag name with the ID
			$tags[$i] = $tag->getCategoryId();
		}
		
		//bulk add tags
		$post->addCategory(array_values($tags))->save();
		
		//add a success message
		$_SESSION['messages'][] = array('success', 'Success rephrasing '.$post['post_type'].'!');
		
		//redirect out
		front()->redirect('/question/'.$post->getPostSlug());
	}
	
	/* Private Methods
	-------------------------------*/
}
